var fs = require('fs');
var coder = require('../public/coder')
var file_util = require('../public/file_util');
var path = require('path');
const Define = require('./ExportDefine')
// const TSParser = require('./TSParser')
// const CSParser = require('./CSParser')
//每张表的处理类
function ExportSheet(index, sheet, head, dir, type) {
    this.type = type;
    this.name = sheet.name;
    console.log('name', this.name);
    this.dir = dir;
    this.excleData = sheet.data;
    this.head = head;
    this.index = index;
    this.config = head.getSheetConfig(index);
    console.log('config', this.config);
    if (this.config && this.config.length > 0) {
        this.langObj = null;
        this.indexObj = {};
        this.indexOfKey = {}
        this.result = {}; //每张表的导出内容
        this.keys = {}; // id列表，对应内容的索引。

        this.dataArray = [];
        this.nameArray = this.excleData[Define.DESC]; // 第一行 说明
        this.keyArray = this.excleData[Define.PROPERTY_NAME]; //第二行 名称
        console.log(' this.keyArray ', this.keyArray)
        this.typeArray = this.excleData[Define.TYPE_NAME]; // 第三行 类型
        this.dbArray = this.excleData[Define.DB_NAME]; // 存档名称，如果有表示这一列数据需要存档。

        this.sheetName = this.config[Define.VALUE];
        this.managerName = this.config[Define.MGR_NAME]
        this.exportID = this.config[Define.IS_EXPORT_ID]
        this.exportType = this.config[Define.EXPORT_TYPE]
        this.nameList = []
        this.typeList = []
        this.dbList = []
        // this.parsers = []
        // this.parsers.push(new TSParser(this))
        // this.parsers.push(new CSParser(this))
    }

}

ExportSheet.prototype.getModuleName = function () {
    return this.managerName;
}

ExportSheet.prototype.getExportType = function () {
    return this.exportType;
}

ExportSheet.prototype.isOk = function () {
    return this.config && this.config.length > 0
}

ExportSheet.prototype.getKeyIndex = function (keyName) {
    for (let index = 0; index < this.keyArray.length; index++) {
        const element = this.keyArray[index];
        if (element == keyName) {
            return index;
        }
    }
    return -1;
}

// ExportSheet.prototype.parseEnumDefine = function () {

// for (let index = 0; index < this.parsers.length; index++) {
//     const parser = this.parsers[index];
//     parser.parseEnumDefine();
// }
// var sheetName = this.sheetName
// console.log(' sheetName ', sheetName)
// var enumName = sheetName.substring(0, 1).toUpperCase() + sheetName.substring(1);
// console.log(' enumName ', enumName)
// var enumObj = "export enum " + enumName + "Enum {\n\t%{data}\n}";
// var enums = "";
// var idIndex = this.getKeyIndex('ID')
// if (idIndex == -1) {
//     idIndex = this.getKeyIndex('id')
//     if (idIndex == -1) {
//         idIndex = this.getKeyIndex('Id')
//     }
// }
// var nameIndex = this.getKeyIndex('name')

// var descIndex = this.getKeyIndex('desc')

// // console.log(' idIndex ', idIndex, 'nameIndex ', nameIndex)
// if (idIndex >= 0 && nameIndex >= 0) {
//     for (var j = Define.DATA_START; j < this.excleData.length; j++) {
//         var curData = this.excleData[j];
//         // console.log(' curData ', curData)
//         // console.log(' curData.length ', curData.length)
//         if (curData.length == 0 || curData[nameIndex] == undefined || curData[idIndex] == undefined) continue;
//         // console.log(' curData[nameIndex] ', curData[nameIndex], '  curData[idIndex]  ', curData[idIndex])
//         let desc = descIndex >= 0 ? curData[descIndex] : '';
//         enums += curData[nameIndex] + " = " + curData[idIndex] + ",// " + desc + "\n\t";
//         // console.log(' enums ', enums)
//     }
// }
// // console.log(' enums ', enums)
// enumObj = enumObj.replace('%{data}', enums);
// this.enumDefine = enumObj;
// this.enumDefineName = enumName;

// // console.log('  this.enumDefine  ', this.enumDefine)

// }

ExportSheet.prototype.parseEnum = function () {
    // var sheetName = this.sheetName
    // console.log(" sheetname", sheetName);

    //生成枚举。
    // var enumName = sheetName.substring(0, 1).toUpperCase() + sheetName.substring(1);
    // this.fileNames = enumName + ': ' + "'" + this.sheetName + "',"
    // var declareObj = 'declare class Json' + enumName + ' {\n\t%{data}\n}'
    // var enumObj = "export enum " + enumName + "Enum {\n\t%{data}\n}";
    // var enums = "";
    // var declares = ''
    var keyIndex = 0;

    for (var k = 0; k < this.keyArray.length; k++) {
        if (this.typeArray[k] && this.typeArray[k] != 'null') {
            var key = this.keyArray[k];
            // let type = this.typeArray[k]
            if (key != undefined) {
                // let tname = Define.TS_TYPE[type.trim()];
                // if (!tname) {
                //     console.error(' tname is null type is ', type)
                // }
                // if (this.nameArray[k]) {
                //     let temp = this.nameArray[k].replace(/\n/g, '') + "\n\t";
                //     enums += key + ",// " + temp;
                //     declares += key + ':' + tname + ";// " + temp;
                // } else {
                //     enums += key + "," + "\n\t";
                //     declares += key + ':' + tname + ";" + "\n\t";
                // }
                this.nameList[keyIndex] = key
                this.typeList[keyIndex] = this.typeArray[k]
                if (this.dbArray && this.dbArray[k]) {
                    this.dbList[keyIndex] = this.dbArray[k]
                } else {
                    // console.warn('k is ', k)
                }
                this.indexOfKey[key] = keyIndex++
            }

        }
    }
    // // console.log(" indexOfKey", this.indexOfKey);
    // enumObj = enumObj.replace('%{data}', enums);
    // this.enumObj = enumObj;
    // this.enumName = enumName;
    // // console.log('this.enumObj  ', this.enumObj)

    // declareObj = declareObj.replace('%{data}', declares);
    // this.declareObj = declareObj;
    // // console.log('this.declareObj  ', this.declareObj)

    // for (let index = 0; index < this.parsers.length; index++) {
    //     const parser = this.parsers[index];
    //     parser.parseEnum();
    // }
}

ExportSheet.prototype.parseData = function () {
    var index = 0;
    for (var j = Define.DATA_START; j < this.excleData.length; j++) {
        var curData = this.excleData[j];
        if (curData.length == 0) continue;
        var item = this.changeObj(this.sheetName, curData, this.typeArray, this.keyArray, this.dbArray, this.indexObj);
        this.keys[curData[0]] = index;
        index++;
        this.dataArray.push(item);
    }
    // console.log('this.sheetName this.dataArray  ', this.dataArray)
    if (this.dataArray.length > 0) {
        this.result["data"] = this.dataArray;
        this.result["key"] = this.keys;
        this.result["type"] = Define.DATA;
        this.result['nameList'] = this.nameList
        this.result['typeList'] = this.typeList
        this.result['dbList'] = this.dbList
        this.result['name'] = this.sheetName
        if (this.indexObj) {
            this.result["index"] = this.indexObj;
        }
    } else {
        // console.log("内容为null ");
        console.log('内容为null export file name ', this.dir.json_path + this.sheetName + ".json")
    }
}

ExportSheet.prototype.changeObj = function (sheetName, curData, typeArray, keyArray, scArray, indexObj) {
    var id = curData[0];
    var obj = [];
    for (var i = 0; i < typeArray.length; i++) {
        // console.log("data "+curData[i]+" type "+typeArray[i]+" key "+keyArray[i]+" sc "+scArray[i]);
        //字母 
        if (typeArray[i] != 'null') {
            obj.push(this.changeValue(curData[i], typeArray[i], sheetName, id, keyArray[i], i - 1, indexObj));
        }
    }
    return obj;
}

ExportSheet.prototype.changeValue = function (value, type, sheetName, id, key, index, indexObj) {

    // console.log(" type ", type, " value ", value, ' sheetName ', sheetName, ' index ', index, ' key ', key);
    var start = type.indexOf('[');
    if (start >= 0) {
        if (value == null || value == "null" || value == "" || value == undefined) return [];
        value = "" + value;
        var end = type.indexOf(']', type.length - 1);
        var t = type.substring(start + 1, end);
        // console.log(" end ",end," start ",start," t ",t);
        if (type.indexOf('[[') >= 0) {
            var list1 = value.split('|');
            var temp1 = [];
            for (var i = 0; i < list1.length; i++) {
                temp1.push(this.changeValue(list1[i], t, sheetName, id, key, index));
            }
            return temp1;
        } else {
            var list2 = value.split(',');
            // console.log(' list2 ', list2)
            var temp2 = [];
            // console.log(' type ', type)
            var t2 = type.substring(start + 1, end);
            // console.log(' t2 ', t2)
            for (var i = 0; i < list2.length; i++) {
                temp2.push(this.changeValue(list2[i], t2, sheetName, id, key));
            }
            // console.log(' temp2 ', temp2)
            return temp2;
        }
    } else {
        // console.log('changeValue  type ', type)
        switch (type) {
            case 'b':
                if (!value) return false;
                return true;
            case 'n':
                if (value == null || value == "null") return 0;
                let v = new Number(value)
                return v
            case 'i':
                if (value == null || value == "null") return 0;
                return parseInt(value);
            case 'f':
                if (value == null || value == "null") return 0.0;
                return parseFloat(value);
            case 's':
                if (value == null || value == "null") return "";
                return value;
            case 'lang': // 根据文件名key 和列名 生成ID并返回生成的ID
                if (value == null || value == "null") return "";
                var langID = sheetName + "_" + key + "_" + id;
                if (!this.langObj) {
                    this.langObj = {}
                }
                this.langObj[langID] = value;
                return langID;
            case 'index':
                var idx = this.indexOfKey[key]
                if (!indexObj[idx]) {
                    indexObj[idx] = {}
                }
                if (value >= 0) {
                    if (!indexObj[idx][value]) {
                        indexObj[idx][value] = []
                    }
                    //console.log("index  value ",value,' id ',id)
                    indexObj[idx][value].push(id);
                    return parseInt(value);
                }
                return 0;
            case 'any':
                return value;
            case 'null':
                return ""

        }

    }

    return "";
}


ExportSheet.prototype.getLangObj = function () {
    return this.langObj;
}



// ExportSheet.prototype.parseClass = function (manager, template) {

// for (let index = 0; index < this.parsers.length; index++) {
//     const parser = this.parsers[index];
//     parser.parseClass(manager, template);
// }
// let export_path = this.dir.class_path;
// if (this.managerName) {
//     export_path = path.join(this.dir.class_path, this.managerName)
// }
// // console.log(' class_path ', export_path)
// file_util.createDir(export_path)
// let className = this.enumName
// let TemplateName = 'Json' + className;
// let classObj = template.replace(/%ClassName%/g, className)
// classObj = classObj.replace('%SheetName%', this.sheetName)
// classObj = classObj.replace('%enum%', this.enumObj)

// classObj = classObj.replace('%TemplateName%', TemplateName)

// let exportStr = ''
// for (var k = 0; k < this.keyArray.length; k++) {
//     if (this.typeArray[k] != 'null') {
//         let tname = Define.TS_TYPE[this.typeArray[k].trim()];
//         if (!tname) {
//             console.log(' tname is null type is ', this.typeArray[k].trim(), className, this.typeArray[k].trim())
//             console.error(' tname is null type is ')
//             tname = ''
//         }
//         var key = "// ";
//         if (this.nameArray[k]) {
//             key += this.nameArray[k].replace(/\n/g, '')
//         }
//         key += "\n\t"; //说明
//         if (typeof (this.keyArray[k]) == "string") {
//             let funcName = this.keyArray[k].substring(0, 1).toUpperCase() + this.keyArray[k].substring(1);
//             key += 'get' + funcName + "(): " + tname + " {\n\t\t"; //getkeyArray[k](){
//             // key += 'return this.getValue(' + this.enumName + 'Enum.' + this.keyArray[k] + ')\n\t';
//             key += 'return this.cfg.' + this.keyArray[k] + ' ;\n\t';
//             key += '}\n\t'
//             exportStr += key;
//         }



//     }
// }
// classObj = classObj.replace('%function%', exportStr)


// file_util.writeFile(path.join(export_path, className + ".ts"), classObj);
// //整合模型管理器信息
// if (manager) {
//     var lowName = className.replace(className[0], className[0].toLowerCase());
//     var proName = lowName + 'Mgr'
//     manager[Define.IMPORT] += 'import { ' + className + ' } from "./' + className + '";\n'
//     var head = 'protected ' + proName + ': ModelManager<' + className + '> = new ModelManager()'
//     manager[Define.HEAD] += head + '\n\t';
//     var init = 'this.' + proName + '.initWithData(cfw.xlsx.get(' + className + '.CLASS_NAME), ' +
//         className + ')'
//     manager[Define.INIT] += init + '\n\t\t';
//     manager[Define.FUNCTION] += 'get' + className + '(id){ return this.' + proName + '.getByID(id,' + className + ')}\n\t\n\t'
//     manager[Define.FUNCTION] += 'get' + className + 'List(){ return this.' + proName + '.getList()}\n\t\n\t'
// }
// }
module.exports = ExportSheet; 